// --- Copyright (c) 2006-2008 Stefan Kyntchev ---
// This software is written and copyrighted by Stefan Kyntchev 
// and BeyondPod Team members. All rights are reserved.
// Author contact: support@beyondpod.mobi
// ------------------------------------------------------------------------
// This file is part of BeyondPod RSS Feed Reader and Podcast manager
// (www.codeplex.com/BeyondPod) 
// BeyondPod is free software: you can redistribute it and/or modify 
// it under the terms of the GNU General Public License as published by 
// the Free Software Foundation, either version 3 of the License, or 
// (at your option) any later version. 
//  
// BeyondPod is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied warranty of 
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
// GNU General Public License for more details. 
//  
// You should have received a copy of the GNU General Public License
// along with BeyondPod. If not, see <http://www.gnu.org/licenses/>
// ------------------------------------------------------------------------
// COPYRIGHT NOTICE: This copyright notice may NOT be removed, obscured or modified 
// without written consent from the author.
// --- End copyright notice --- 


using System;
using System.Collections.Generic;
using System.IO;
using svs.Mobile.BeyondMedia.FeedCore.RSS.Entities;

namespace svs.Mobile.BeyondMedia.FeedCore.RSS
{
	public class EnclosureDownloadHistory
	{
		private static Dictionary<int, long> m_history = null;
		private static bool m_modified;

		private static Dictionary<int, long> History
		{
			get
			{
				if (m_history == null)
					LoadHistory();

				return m_history;
			}
		}

		public static bool HasEntryFor(string enclosurePath)
		{
			CoreHelper.WriteTraceEntry(string.Format("Checking download History for: {0} (hash:{1})...", enclosurePath, enclosurePath.GetHashCode()));
			var found = History.ContainsKey(enclosurePath.GetHashCode());
			CoreHelper.WriteTraceEntry("Has Entry: " + found);
			return found;
		}

		public static void AddEnclosure(string enclosurePath)
		{
			CoreHelper.WriteTraceEntry(string.Format("Inserted download History for: {0} (hash:{1})...", enclosurePath, enclosurePath.GetHashCode()));
			History[enclosurePath.GetHashCode()] = DateTime.Now.Ticks;
			m_modified = true;
		}

		public static void RemoveEnclosure(string enclosurePath)
		{
			if (HasEntryFor(enclosurePath))
			{
				CoreHelper.WriteTraceEntry(string.Format("Deleted download History for: {0} (hash:{1})", enclosurePath, enclosurePath.GetHashCode()));
				History.Remove(enclosurePath.GetHashCode());
			}

			m_modified = true;
		}

		public static void ClearHistory()
		{
			History.Clear();
			m_modified = true;
		}

		private static void LoadHistory()
		{
			FileStream fs = null;
			m_history = new Dictionary<int, long>();

			if (File.Exists(Configuration.EnclosureDownloadHistoryFilePath))
			{
				try
				{
					fs = File.OpenRead(Configuration.EnclosureDownloadHistoryFilePath);
					BinaryReader br = new BinaryReader(fs);

					while (br.PeekChar() != -1)
					{
						int key = br.ReadInt32();
						long value = br.ReadInt64();

						m_history[key] = value;
					}

					fs.Close();
				}
				catch (Exception ex)
				{
					CoreHelper.WriteLogEntry("Unable to load download history. Reason: " + ex.Message);
				}
				finally
				{
					if (fs != null)
						fs.Close();
				}
			}

			m_modified = false;
		}

		public static void SaveHistory()
		{
			if (!m_modified)
				return;

			lock (m_history)
			{
				CoreHelper.WriteTraceEntry("Saving Download History...");
				string tempPath = Configuration.EnclosureDownloadHistoryFilePath + ".tmp";

				FileStream fs = null;
				try
				{
					fs = File.OpenWrite(tempPath);
					BinaryWriter bw = new BinaryWriter(fs);

					foreach (KeyValuePair<int, long> entry in History)
					{
						bw.Write(entry.Key);
						bw.Write(entry.Value);
					}
					fs.Close();
				}
				catch (Exception ex)
				{
					CoreHelper.WriteLogEntry("Unable to save download history. Reason: " + ex.Message);
				}
				finally
				{
					if (fs != null)
						fs.Close();
				}

				//Rename the temp file
				try
				{
					File.Copy(tempPath, Configuration.EnclosureDownloadHistoryFilePath, true);
					File.Delete(tempPath);
					m_modified = false;
				}
				catch (Exception ex)
				{
					CoreHelper.WriteLogEntry("Unable to copy download history! " + ex.Message);
				}
			}
		}

		public static void AddAllEnclosures(RssFeed feed)
		{
			foreach (RssFeedItem item in feed.Items)
			{
				if (item.Enclosure != null)
					AddEnclosure(item.Enclosure.LocalFileName);
			}
		}

		public static void RemoveAllEnclosuresForFeed(RssFeed feed)
		{
			foreach (RssFeedItem item in feed.Items)
			{
				if (item.Enclosure != null)
					RemoveEnclosure(item.Enclosure.LocalFileName);
			}
		}
	}
}